package com.sunway.logger.conf;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

	@Value("${elasticsearch.host:localhost}")
	private String host; // elastic search的地址

	@Value("${elasticsearch.port:9300}")
	private Integer port; // elastic search的端口

	@SuppressWarnings({ "resource", "unused" })
	@Bean
	public TransportClient TransportClient() throws UnknownHostException {
		TransportClient client = null;

		// 暂时不用
		//@formatter:off
		Settings settings = Settings.builder()
	            .put("client.transport.nodes_sampler_interval", "5s")
	            .put("client.transport.sniff", false)
	            .put("transport.tcp.compress", true)
	            .put("cluster.name", "clusterName")
	            .put("xpack.security.transport.ssl.enabled", true)
	            .build();
		//@formatter:on

		client = new PreBuiltTransportClient(Settings.EMPTY)
				.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port))
				.addTransportAddress(new TransportAddress(InetAddress.getByName("47.100.255.47"), port));

		return client;
	}

	@Bean
	public NodeClient NodeClient() {
		
		//@formatter:off
		Settings settings = Settings.builder()
	            .put("client.transport.nodes_sampler_interval", "5s")
	            .put("client.transport.sniff", false)
	            .put("transport.tcp.compress", true)
	            .put("cluster.name", "clusterName")
	            .put("xpack.security.transport.ssl.enabled", true)
	            .build();
		//@formatter:on
		// 这个还没有搞清楚怎么用.
		NodeClient client = new NodeClient(settings, null);
		 
		return client;
	}

	@Bean
	public RestClient RestClient() {
		RestClient client = RestClient.builder(new HttpHost(host, port)).build();
		return client;
	}
}
